using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;

using UwinEducation.Shared.Models;


namespace UwinEducation.Infrastructure.Repositories
{
    public class RoleRepository : Repository<Role, Guid>, IRoleRepository
    {
        public RoleRepository(ApplicationDbContext context) : base(context)
        {
        }
        /// <summary>
        /// 分页查询角色列表
        /// </summary>
        public async Task<PagedResult<Role>> GetPagedListAsync(PageRequest pageRequest)
        {
            var query = _context.Roles.AsQueryable();

            // 如果有搜索条件，添加过滤
            //if (!string.IsNullOrEmpty(pageRequest.Search))
            //{
            //    query = query.Where(r => r.Name.Contains(pageRequest.Search));
            //}

            var total = await query.CountAsync();
            var items = await query
                .Skip((pageRequest.PageIndex - 1) * pageRequest.PageSize)
                .Take(pageRequest.PageSize)
                .ToListAsync();

            return new PagedResult<Role>
            {
                Total = total,
                Items = items
            };
        }
        /// <summary>
        /// 根据ID获取角色
        /// </summary>
        public async Task<Role> GetByIdAsync(Guid id)
        {
            return await _context.Roles
                .FirstOrDefaultAsync(r => r.Id == id);
        }

        /// <summary>
        /// 创建角色
        /// </summary>
        public async Task CreateAsync(Role role)
        {
            await _context.Roles.AddAsync(role);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 更新角色
        /// </summary>
        public async Task UpdateAsync(Role role)
        {
            _context.Roles.Update(role);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        public async Task DeleteAsync(Guid id)
        {
            var role = await _context.Roles.FindAsync(id);
            if (role != null)
            {
                _context.Roles.Remove(role);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 为角色分配菜单权限
        /// </summary>
        public async Task AssignMenusAsync(Guid roleId, List<string> menuCodes)
        {
            // 先删除原有的角色权限关系
            var existingRolePermissions = await _context.RolePermissions
                .Where(rp => rp.RoleId == roleId)
                .ToListAsync();
            _context.RolePermissions.RemoveRange(existingRolePermissions);

            //根据menuCodes查询permissionId
            var permissions= await _context.Permissions.Where(p => menuCodes.Contains(p.Code)).ToListAsync();


            // 添加新的角色权限关系
            var rolePermissions = permissions.Select(permission => RolePermission.Create(roleId, permission.Id, permission.Code));
            await _context.RolePermissions.AddRangeAsync(rolePermissions);

            await _context.SaveChangesAsync();
        }
        /// <summary>
        /// 检查角色名是否已存在
        /// /// </summary>
        /// <param name="name"></param>
        /// <param name="excludeId"></param>
        /// <returns></returns>
        public Task<bool> ExistsByNameAsync(string name, Guid? excludeId = null)
        {
            return _context.Roles.AnyAsync(r => r.Name == name && r.Id != excludeId);

            //return _context.Roles
            //    .Where(r => r.Name == name && (!excludeId.HasValue || r.Id != excludeId.Value))
            //    .AnyAsync();
        }
    }
} 